package com.handycraftz.site.server.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HandyCraftzValidator {

	public static boolean validateUrl(String url) {
		Pattern p = Pattern.compile("http://[A-Za-z0-9.-]{3,}.[A-Za-z]{3}");
		Matcher m = p.matcher(url);
		if (!m.find()) {
			return false;
		}

		return true;
	}

	public static boolean validateNullString(String value) {
		if (value.equalsIgnoreCase("") || value.equalsIgnoreCase(null)) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean validateEmail(String email) {
		// Checks for email addresses starting with
		// inappropriate symbols like dots or @ signs.
		Pattern p = Pattern.compile("^\\.|^\\@");
		Matcher m = p.matcher(email);
		if (m.find()) {
			return false;
		}
		// Checks for email addresses that start with
		// www. and prints a message if it does.
		p = Pattern.compile("^www\\.");
		m = p.matcher(email);
		if (m.find()) {
			return false;
		}
		// Checks for occurrence of @
		p = Pattern.compile("@");
		m = p.matcher(email);
		if (!(m.find())) {
			return false;
		}

		p = Pattern.compile(".+@.+\\.[a-z]+");
		m = p.matcher(email);
		if (!m.find()) {
			return false;
		}

		p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
		m = p.matcher(email);
		StringBuffer sb = new StringBuffer();
		boolean result = m.find();
		boolean deletedIllegalChars = false;

		while (result) {
			deletedIllegalChars = true;
			m.appendReplacement(sb, "");
			result = m.find();
		}
		// Add the last segment of email to the new String
		m.appendTail(sb);
		email = sb.toString();
		if (deletedIllegalChars) {
			return false;
		}

		// Valid email
		return true;
	}

}
